package com.luo.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.junit.runners.Parameterized.Parameters;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.luo.domain.User;
import com.luo.service.UserService;
import com.luo.utils.AjaxJson;
import com.luo.utils.JsonConversion;

@Controller  
public class UserController {  

    //(注入Service层)
    @Resource  
    private UserService userService;  

    
    @RequestMapping("/")    
    public ModelAndView getLogin(HttpSession session){      
        ModelAndView mav = new ModelAndView("login");   
        return mav;    
    } 
    
    @RequestMapping("/detail")    
    public ModelAndView toDetail(User user){    
        
        ModelAndView mav = new ModelAndView("detail");   
        mav.addObject("user",user);
        return mav;    
    } 
    
    //到编辑页面
    @RequestMapping("/toEdit")    
    public ModelAndView toEdit(){      
        ModelAndView mav = new ModelAndView("detail");  
        return mav;    
    } 
    
    @ResponseBody
    @RequestMapping(value="/updateByUserId",produces = "application/json; charset=UTF-8")  
    public AjaxJson edit(User user){ 
        AjaxJson j = new AjaxJson();

        try {
            userService.updateByUserId(user);
            j.setSuccess(true);
            j.setMsg("修改已完成");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            j.setSuccess(false);
        }
        
        return j;
    }  
    
    
    
    @RequestMapping(value="/login",method=RequestMethod.POST)    
    public ModelAndView login(
            @RequestParam(value="userName") String userName,
    		@RequestParam(value="password") String password,
    		HttpSession session){      
        ModelAndView mav = new ModelAndView("index");   
        System.out.println(userName + ":" + password);
        
        //执行数据查询操作
        User user = userService.loginUser(userName, password);
        
        //需要在这边进行一个判断 判断用户是否为空
        if(user!=null){
            
            System.out.println(user.getUserName() + ":" + user.getUserPassword());
            mav.addObject("user", user); 
            session.setAttribute("user", user);
           
            return mav;    
            
        }else {
               //根据你提供的用户名和密码 我找不到这个用户 就是意味着你的账号或者密码错误了
            String message = "用户名或者密码错误 ";
          
            mav.addObject("msg", message);
            mav.setViewName("login");
          
            return mav;
        }
          
       
    } 
    
    
    @ResponseBody
    @RequestMapping(value="/checkUser")  
    public AjaxJson checkUser(String userName){ 
        AjaxJson j = new AjaxJson();
      
        User user= userService.checkUser(userName);
        
        if(user!=null){
                //查询到了 意味着我找到了  我就不让你用这个名字
            j.setSuccess(true);
            j.setMsg("查询到了用户");
        }else {
            j.setSuccess(false);
        }
        
        
        return j;
    }  
    
    
    
    @RequestMapping("/logout")    
    public ModelAndView getIndex(HttpSession session){   
    	User user = getLoginUser(session);
    	if(user!=null){
    		session.removeAttribute("user");
    	}
        ModelAndView mav = new ModelAndView("login");   
        return mav;    
    }

    /**
     * @param session
     * @return
     */
    public User getLoginUser(HttpSession session) {
        User user = (User)session.getAttribute("user");
        User loginuser = userService.loginUser(user.getUserName(), user.getUserPassword());
        return user;
    }    
    
    @RequestMapping(value="/signIn",method=RequestMethod.POST)    
    public ModelAndView login(@RequestParam(value="userName") String userName,
    		@RequestParam(value="password") String password){      
        ModelAndView mav = new ModelAndView("sign_in");   
        System.out.println(userName + ":" + password);
        boolean seccuss =  userService.signInUser(userName, password);
        mav.addObject("msg", seccuss);  
        return mav;    
    } 
    
    @RequestMapping("/toSignIn")    
    public ModelAndView toSignIn(HttpSession session){      
        ModelAndView mav = new ModelAndView("sign_in");   
        return mav;    
    } 
    
    
    

    @RequestMapping("/toTable")    
    public ModelAndView toTable(HttpSession session){      
        ModelAndView mav = new ModelAndView("layuiTable");   
        return mav;    
    } 
    
    @RequestMapping(value="/list",produces = "application/json; charset=UTF-8")    
    @ResponseBody
    public String list(HttpSession session){      
        Map map = new HashMap<>();
        List<User> list = userService.listUser();
        if (list!=null && list.size()>0) {
            map.put("code", 0);
            map.put("msg", "success");
            map.put("data", list);
        }else {
            map.put("code", -1);
            map.put("msg", "无数据");
            map.put("data", "");
        }
        return  JsonConversion.writeMapJSON(map);
    }   
    
    
    
    @ResponseBody
    @RequestMapping(value="/findListByPage",produces = "application/json; charset=UTF-8")
    public String findListByPage(
            @RequestParam(value="page")int page,
            @RequestParam(value="limit")int limit,
            HttpServletRequest request, 
            Model model)
    {
        String userName = request.getParameter("userName");//获取浏览器携带过来的参数userName
        int start = (page-1)*limit + 1; //分页操作 见找规律
        int end = page*limit;
        int count = 0;
        
        List<User> userList = null;
        if(userName!=null&&userName!=""){
                //如果取到了参数 我就走三个参数的方法 
             userList = userService.findListByUserName(start,end,userName);
             count = userService.getCountByUserName(userName);
        }else {
              //如果取不到userName 说明查询的是全部 没有携带第三个参数
            userList = userService.findListByPage(start,end);
            count = userService.getCount();
        }
        
        //拼接成json字符串  满足layui定义的表格渲染格式
       Map map = new HashMap<>();
       if (userList!=null && userList.size()>0) {
           map.put("code", 0);
           map.put("msg", "success");
           map.put("count", count);
           map.put("data", userList);
       }else {
           map.put("code", -1);
           map.put("msg", "无数据");
           map.put("data", "");
       }
       return  JsonConversion.writeMapJSON(map);
    }
    
    
    
    
 /*   @ResponseBody
    @RequestMapping(value="/findListByPage",produces = "application/json; charset=UTF-8")
    public String findListByPage(
            @RequestParam(value="page")int page,
            @RequestParam(value="limit")int limit,
            Model model)
    {
        int start = (page-1)*limit + 1;
        int end = page*limit;
        int count = userService.getCount();
       List<User> userList = userService.findListByPage(start,end);
       Map map = new HashMap<>();
       if (userList!=null && userList.size()>0) {
           map.put("code", 0);
           map.put("msg", "success");
           map.put("count", count);
           map.put("data", userList);
       }else {
           map.put("code", -1);
           map.put("msg", "无数据");
           map.put("data", "");
       }
       return  JsonConversion.writeMapJSON(map);
    }*/
    
    
    
    @RequestMapping("/listUser")    
    public ModelAndView listUser(HttpSession session){      
        User user = (User) session.getAttribute("user");
        
        ModelAndView mav = new ModelAndView();   
        if (user!=null){
        List<User> list = userService.listUser();
        mav.setViewName("list");
        mav.addObject("list", list);  
        }else{
        mav.setViewName("login");
        }
        return mav;    
    }   
    
    
    @RequestMapping(value="/toSearch")
    public String toSearch(){
        
        return "ajax";
    }
    
/*    @RequestMapping(value="/searchUserByName")
    public String searchUser(@RequestParam(value="userName") String userName, Model model){
        
        
        List<User> userList = userService.searchUserByName(userName);
        
        if(userList!=null && userList.size()!=0){
            model.addAttribute("userList", userList);
        }else{
            String message="无此用户信息";
            model.addAttribute("msg", message);
            }
       return "search";
    }*/
    
    @RequestMapping(value="/searchUserByName")
    public String searchUser(@RequestParam(value="userName") String userName, Model model){
        
        if(userName=="" || userName ==null){
            List<User> list = userService.listUser();
            model.addAttribute("list", list);
        }else{
        
        List<User> userList = userService.searchUserByName(userName);
        
        if(userList!=null && userList.size()!=0){
            model.addAttribute("userList", userList);
        }else{
            String message="无此用户信息";
            model.addAttribute("msg", message);
            }
        }
      //  return "search";
         return "list";
    }
    
    @RequestMapping(value="/deleteUserById")
    public String deleteUserById(@RequestParam(value="userId") String userId){
            
        //这里就是Controller层调用Service层
        
        
        
        userService.deleteUserById(userId);
        
         //进行页面的返回并且还要有对应的值 那么我们就需要让浏览器再发送一个请求 发送一个查询所有用户的请求  就是
        //http://localhost:8080/ssm_maven/listUser
        
            //重定向写法
        return "redirect:/listUser";
    }
    
    @ResponseBody
    @RequestMapping(value="/deleteUser")
    public AjaxJson deleteUse( String userId){
            
        AjaxJson j = new AjaxJson();
        
        try {
            userService.deleteUserById(userId);
            j.setMsg("删除成功");
            j.setSuccess(true);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            j.setSuccess(false);
        }
        return j;
    }
} 

